import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { Card, Table, InputNumber, Button, Affix, message } from 'antd';
import { connect, history } from 'umi';
import Contanst from '@/config/contanst';
import SearchForm from './searchForm'
import { saveSetCardByCourseId } from './service';
const SupCard = props => {
  const { dispatch, allCardByCourseId, courseId } = props;
  const [bigClassValue, setBigClassValue] = useState("");
  const [bigClassSingleValue, setBigClassSingleValue] = useState({});
  const [bigClassKeys, setBigClassKeys] = useState([]);
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeLesson/queryAllCardByCourseId',
        payload: {
          courseId: courseId
        },
      }).then((result) => {
        init(result)
      })
    }
  }, []);
  const init = (courseCardlist) => {
    let _ = courseCardlist.filter((item) => {
      if (item.courseId) {
        return item.cardId
      }
    })
    let $ = _.map((item) => item.cardId)
    setBigClassKeys($)
    courseCardlist.map((item) => {
      if ($.includes(item.cardId)) {
        bigClassSingleValue[item.cardId] = item.costPerClassPersonGroup
      }
    })
    setBigClassSingleValue(bigClassSingleValue)
  }
  /**
 * 大班课统一设置价格
 */
  const bigClassSetting = value => {
    setBigClassSingleValue({})
    setBigClassValue(value)
  }
  /**
 * 大班课单个设置价格
 * @param {*} value 
 */
  const bigSingleClassSetting = (value, record) => {
    let _bigClassSingleValue = { ...bigClassSingleValue }
    _bigClassSingleValue[record.cardId] = value
    setBigClassSingleValue(_bigClassSingleValue)
  }
  console.log('bigClassSingleValue===>', bigClassSingleValue)
  // console.log('bigClassValue===>', bigClassValue)
  // console.log('bigClassKeys>>>', bigClassKeys)
  const reset = () => {
    setBigClassSingleValue({})
    setBigClassValue("")
  }

  /**
   *检索
   * @param {*} values 
   */
  const _search = (values) => {
    let params = {
      courseId: courseId,
    }
    if (values.cardName) {
      params.cardName = values.cardName
    }
    if (values.cardType) {
      params.cardType = values.cardType
    }
    dispatch({
      type: 'cubeLesson/queryAllCardByCourseId',
      payload: {
        ...params
      },
    }).then((result) => {
      init(result)
      reset()
    })
  }
  const changeSelectCard = (selectedRowKeys) => {
    setBigClassKeys(selectedRowKeys)
  }

  /**
   * 保存支持的会员卡
   */
  const submitSupCard = async () => {
    const hide = message.loading('正在保存');
    try {
      let supCard = [];
      if (bigClassKeys && bigClassKeys.length > 0) {
        bigClassKeys.map((item) => {
          let cardObj = {
            courseId: courseId,
            cardId: item
          }
          if (bigClassSingleValue) {
            if (bigClassSingleValue[item]) {
              cardObj['costPerClassPersonGroup'] = bigClassSingleValue[item]
            } else if (bigClassValue) {
              cardObj['costPerClassPersonGroup'] = bigClassValue
            }
          } else if (bigClassValue) {
            cardObj['costPerClassPersonGroup'] = bigClassValue
          }
          supCard.push(cardObj);
        })
      }
      let result = await saveSetCardByCourseId(supCard);
      hide();
      if (result.code === 0) {
        message.success('保存成功，即将刷新');
        return true;
      } else {
        message.error(result.message);
        return false;
      }
    } catch (error) {
      console.log('error===>', error)
      hide();
      message.error('保存失败，请重试');
      return false;
    }
  }
  const renderCallBack = useCallback((text, record)=>{
    return <><span>每节课收费</span>&nbsp;&nbsp;&nbsp;<InputNumber min={0} onChange={value => bigSingleClassSetting(value, record)} value={bigClassSingleValue[record.cardId] || bigClassValue} />&nbsp;&nbsp;元/人</>
  },[bigClassSingleValue,bigClassValue])
  return <>
    <Card title="会员卡信息" style={{ marginTop: 32 }}>
      <SearchForm search={(values) => _search(values)} />
      <Table
        rowKey="cardId"
        size="small"
        pagination={false}
        columns={ [
          {
            title: '会员卡名称',
            dataIndex: 'cardName',
          },
          {
            title: '会员卡类型',
            dataIndex: 'cardType',
            render: text => <span>{Contanst.MemberCardTypeMap[text]}</span>
          },
          {
            title: <><span>&nbsp;&nbsp;&nbsp;统一设置</span>&nbsp;&nbsp;&nbsp;&nbsp;<InputNumber min={0} onChange={bigClassSetting} />&nbsp;&nbsp;元/人</>,
            dataIndex: 'costPerClassPersonGroup',
            render: (text, record)=>renderCallBack(text, record)
          },
        ]}
        dataSource={allCardByCourseId}
        rowSelection={{
          selectedRowKeys: bigClassKeys,
          onChange: (selectedRowKeys, selectedRows) => {
            changeSelectCard(selectedRowKeys)
          }
        }}
      />
    </Card>
    <Affix offsetBottom={10}>
      <Button type="primary" style={{ marginTop: 10 }} onClick={submitSupCard}>
        提交
      </Button>
    </Affix>
  </>
}
export default connect(({ loading, cubeLesson }) => ({
  allCardByCourseId: cubeLesson.allCardByCourseId
}))(SupCard);